package com.zero.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import com.zero.user.User;
import com.zero.util.Codec;

/**
 * 客服端发送线程类
 * 
 * @author Zero
 *
 */
public class ClientSendThread extends Thread {
	private ChatView chatView;
	private static PrintWriter printWriter;

	public ClientSendThread(User user, ChatView chatView) throws IOException {
		this.chatView = chatView;
		printWriter = new PrintWriter(user.getSocket().getOutputStream());
	}

	/**
	 * 连接服务端并发送当前连接用户的信息
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public static void clientConServer(User user) throws UnsupportedEncodingException {
		printWriter.write("connect\n");
		printWriter.flush();
		printWriter.write(Codec.encode(user.getName()) + "\n");
		printWriter.flush();
		printWriter.write(Codec.encode(user.getNickname()) + "\n");
		printWriter.flush();
		printWriter.write(Codec.encode(user.getPassword()) + "\n");
		printWriter.flush();
	}

	/**
	 * 私聊
	 * 
	 * @param message 消息
	 * @param to      收信人姓名
	 * @throws UnsupportedEncodingException
	 */
	public static void clientSend(String message, String to) throws UnsupportedEncodingException {
		printWriter.write("send\n");
		printWriter.flush();
		printWriter.write(Codec.encode(to) + "\n");
		printWriter.flush();
		printWriter.write(Codec.encode(message) + "\n");
		printWriter.flush();
	}

	/**
	 * 发送群体消息
	 * 
	 * @param message
	 * @throws UnsupportedEncodingException
	 */
	public static void clientSendAll(String message) throws UnsupportedEncodingException {
		printWriter.write("sendAll\n");
		printWriter.flush();
		printWriter.write(Codec.encode(message) + "\n");
		printWriter.flush();
	}

	/**
	 * 客服端断开请求
	 */
	public static void disconnect() {
		printWriter.write("disconnect\n");
		printWriter.flush();
	}

	@Override
	public void run() {
		while (true) {
			try {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date date = new Date();
				printWriter.write("HeartBeat\n");
				printWriter.flush();
				printWriter.write(format.format(date) + "\n");
				printWriter.flush();
				sleep(30000);// 30秒发送一次
			} catch (InterruptedException e) {
				SwingUtilities.invokeLater(
						() -> JOptionPane.showMessageDialog(chatView, "中断异常", "提示", JOptionPane.WARNING_MESSAGE));
			}
		}
	}
}
